package service

import android.app.*
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import android.util.Log
import com.wsq.service.MainActivity
import com.wsq.service.R

class MyService : Service() {

    companion object{
        const val channelID = "10086"
        const val channelName = "default"
    }


    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.e(MainActivity.TAG, intent!!.getStringExtra("key")!!)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            startForegroundDemo()
        }

        return super.onStartCommand(intent, flags, startId)
    }

    override fun onBind(intent: Intent): IBinder {
        TODO("Return the communication channel to the service.")
    }


    /**
     * Android 9以后，需要在onStartCommand中请求服务前台运行
     */
    private fun startForegroundDemo(){
        val pendingIntent: PendingIntent =
            Intent(this, MainActivity::class.java).let { notificationIntent ->
                PendingIntent.getActivity(this, 0, notificationIntent, 0)
            }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val nm = getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager
            nm?.let { createNotificationChannel(it) }

            val notification: Notification = Notification.Builder(this, channelID)
                    .setContentTitle("前台服务")
                    .setContentText("前台服务")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentIntent(pendingIntent)
                    .setTicker("ticker")
                    .build()


            // Notification ID cannot be 0.
            startForeground(12, notification)
        }


    }


    private fun createNotificationChannel(manager: NotificationManager) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (manager.getNotificationChannel(channelID) == null) {
                val notificationChannel = NotificationChannel(
                    channelID,
                    channelName,
                    NotificationManager.IMPORTANCE_LOW
                )

                notificationChannel.description = "notification_channel_description"

                manager.createNotificationChannel(notificationChannel)
            }

        }



    }
}